<script setup>
import {ref} from "vue";
import ChannelSelect from "@/components/article/ChannelSelect.vue";
import {Plus} from "@element-plus/icons-vue";
import {QuillEditor} from "@vueup/vue-quill";
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import {addArticle, editArticle, getArticleCategoryList, getArticleDetail, uploadImage} from "@/api/article.js";
import {ElMessage} from "element-plus";
import {formatDateTimeY4M2D2} from "@/utils/format.js";

// 抽屉
const visibleDrawer = ref(false)
// 图片
const imgUrl = ref('')
// 文本编辑器
const editorRef = ref(null)

const defaultForm = {
	title: '',
	cateId: '',
	cateName: '',
	imgUrl: '',
	pubDate: '',
	content: '',
	state: ''
}

// 准备数据
const formModel = ref({...defaultForm})

const channelList = ref([])
const getChannelList = async () => {
	const res = await getArticleCategoryList()
	channelList.value = res.data.records
}
getChannelList()

const open = async row => {
	visibleDrawer.value = true
	if (row.id) {
		const data = await getArticleDetail(row.id)
		if (data && data.data) {
			formModel.value = data.data
			imgUrl.value = data.data.imgUrl || ''
			editorRef.value.setHTML(data.data.content || '')
		}
	} else {
		// 重置表单
		formModel.value = {...defaultForm}
		// 重置图片地址+文本编辑器
		imgUrl.value = ''
		editorRef.value.setHTML('')
	}
}

const onSelectFile = (uploadFile) => {
	imgUrl.value = URL.createObjectURL(uploadFile.raw)      // 预览图片
	formModel.value.imgUrl = uploadFile.raw
}

const emit = defineEmits(['success'])

const onPublish = async (state) => {
	formModel.value.state = state
	// 通过cateId拿到cateName
	channelList.value.forEach(item => {
		if (item.id === formModel.value.cateId) {
			formModel.value.cateName = item.cateName
		}
	})
	formModel.value.pubDate = formatDateTimeY4M2D2(new Date())
	// 编辑
	if (formModel.value.id) {
		// 如果文件发送了变化
		if (formModel.value.imgUrl !== imgUrl.value) {
			const fd = new FormData()
			fd.append('file', formModel.value.imgUrl)
			const {data: filePath} = await uploadImage(fd)
			formModel.value.imgUrl = filePath
		}
		formModel.value.content = editorRef.value.getHTML()
		await editArticle(formModel.value)
		ElMessage.success('编辑成功')
		visibleDrawer.value = false
		emit('success')
	} else {
		const fd = new FormData()
		fd.append('file', formModel.value.imgUrl)
		const {data: filePath} = await uploadImage(fd)
		formModel.value.imgUrl = filePath
		formModel.value.content = editorRef.value.getHTML()
		await addArticle(formModel.value)
		ElMessage.success('添加成功')
		visibleDrawer.value = false
		// 通知父组件刷新列表
		emit('success', 'add')
	}
}

defineExpose({open})
</script>

<template>
	<el-drawer
			v-model="visibleDrawer"
			:title="formModel.id ? '编辑文章' : '添加文章'"
			direction="rtl"
			size="50%"
	>
		<!-- 发表文章表单 -->
		<el-form :model="formModel" ref="formRef" label-width="100px">
			<el-form-item label="文章标题" prop="title">
				<el-input v-model="formModel.title" placeholder="请输入标题"></el-input>
			</el-form-item>
			<el-form-item label="文章分类" prop="cateId">
				<channel-select
						v-model="formModel.cateId"
						width="100%"
				></channel-select>
			</el-form-item>
			<el-form-item label="文章封面" prop="imgUrl">
				<!--
					需要关闭自动上传
				-->
				<el-upload class="avatar-uploader"
				           :auto-upload="false"
				           :show-file-list="false"
				           :on-change="onSelectFile"
				>
					<img v-if="imgUrl" :src="imgUrl" class="avatar" alt="">
					<el-icon v-else class="el-icon-plus avatar-uploader-icon">
						<Plus/>
					</el-icon>
				</el-upload>
			</el-form-item>
			<el-form-item label="文章内容" prop="content">
				<div class="editor">
					<quill-editor theme="snow" v-model="formModel.content" content-type="html" ref="editorRef">
					</quill-editor>
				</div>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="onPublish(1)">发布</el-button>
				<el-button type="info" @click="onPublish(0)">草稿</el-button>
			</el-form-item>
		</el-form>
	</el-drawer>
</template>

<style scoped lang="scss">
.avatar-uploader {
	:deep {
		.avatar {
			width: 400px;
			height: 240px;
			display: block;
		}

		.el-upload {
			border: 1px dashed var(--el-border-color);
			border-radius: 6px;
			cursor: pointer;
			position: relative;
			overflow: hidden;
			transition: var(--el-transition-duration-fast);
		}

		.el-upload:hover {
			border-color: var(--el-color-primary);
		}

		.el-icon.avatar-uploader-icon {
			font-size: 28px;
			color: #8c939d;
			width: 400px;
			height: 240px;
			text-align: center;
		}
	}
}

.editor {
	width: 100%;

	:deep(.ql-editor) {
		min-height: 200px;
	}
}
</style>